<template>
  <view>
    <base-board
      :board-matrix="localBoardMatrix"
      :selected-piece="selectedPiece"
      :possible-moves="localPossibleMoves"
      :checked-king="checkedKing"
      :moving-piece="movingPiece"
      :capturing-piece="capturingPiece"
      :promoting-piece="promotingPiece"
      @square-click="onSquareClick"
    />
    
    <!-- 升变对话框 -->
    <view class="promotion-dialog" v-if="showPromotionDialog">
      <view class="dialog-mask" 
            @tap.stop="showPromotionDialog = false"
            @touchmove.stop.prevent></view>
      <view class="promotion-options">
        <view class="option"
              v-for="type in ['queen', 'rook', 'bishop', 'knight']"
              :key="type"
              @tap.stop="onPromotionSelect(type)">
          <image class="promotion-piece-image"
                 :src="`../../static/images/pieces/${promotionColor}_${type}.png`"/>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import BaseBoard from './base-board.vue'
import MoveCalculator from './move-calculator.js'

export default {
  name: 'Chessboard',
  components: {
    BaseBoard
  },
  props: {
    language: {
      type: String,
      default: 'zh_CN'
    },
    boardMatrix: {
      type: Array,
      required: true,
      default: () => Array(8).fill().map(() => Array(8).fill(null))
    },
    selectedPiece: {
      type: Object,
      default: null
    },
    possibleMoves: {
      type: Array,
      default: () => []
    },
    gameStatus: {
      type: String,
      required: true,
      validator: value => ['playing', 'checkmate', 'draw', 'timeout'].includes(value)
    },
    currentPlayer: {
      type: String,
      required: true,
      validator: value => ['white', 'black'].includes(value)
    },
  },
  data() {
    return {
      localBoardMatrix: Array.isArray(this.boardMatrix) ? this.boardMatrix.map(row => [...row]) : Array(8).fill().map(() => Array(8).fill(null)),
      movingPiece: null,
      capturingPiece: null,
      checkedKing: null,
      promotingPiece: null,
      moveHistory: [],
      positionHistory: [],
      castlingState: {
        whiteKingMoved: false,
        blackKingMoved: false,
        whiteLeftRookMoved: false,
        whiteRightRookMoved: false,
        blackLeftRookMoved: false,
        blackRightRookMoved: false
      },
      movesSinceLastCaptureOrPawn: 0,
      enPassantTarget: null,
      showPromotionDialog: false,
      promotionColor: '',
      localPossibleMoves: Array.isArray(this.possibleMoves) ? [...this.possibleMoves] : [],
      promotionPosition: null,
      isValidMoveResult: false,
      lastMoveCaptured: null,
      moveCalculator: null
    }
  },
  watch: {
    boardMatrix: {
      handler(newVal) {
        if (!Array.isArray(newVal)) {
          this.localBoardMatrix = Array(8).fill().map(() => Array(8).fill(null))
          return
        }
        // 使用深拷贝确保数据独立性
        this.localBoardMatrix = JSON.parse(JSON.stringify(newVal))
        // 强制更新视图
        this.$forceUpdate()
      },
      deep: true,
      immediate: true
    },
    possibleMoves: {
      handler(newVal) {
        this.localPossibleMoves = Array.isArray(newVal) ? [...newVal] : []
      },
      immediate: true
    }
  },
  created() {
    this.moveCalculator = new MoveCalculator(this.localBoardMatrix)
    this.initBoard()
  },
  methods: {
    initBoard() {
      this.localBoardMatrix = Array(8).fill().map(() => Array(8).fill(null))
      const initialPosition = [
        ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook'],
        ['pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn']
      ]

      // 设置黑方棋子
      for (let col = 0; col < 8; col++) {
        this.localBoardMatrix[0][col] = { type: initialPosition[0][col], color: 'black' }
        this.localBoardMatrix[1][col] = { type: initialPosition[1][col], color: 'black' }
      }

      // 设置白方棋子
      for (let col = 0; col < 8; col++) {
        this.localBoardMatrix[6][col] = { type: initialPosition[1][col], color: 'white' }
        this.localBoardMatrix[7][col] = { type: initialPosition[0][col], color: 'white' }
      }

      // 更新moveCalculator的棋盘状态
      this.moveCalculator.updateBoardMatrix(this.localBoardMatrix)

      this.resetGameState()
    },

    resetGameState() {
      this.$emit('update:selectedPiece', null)
      this.localPossibleMoves = []
      this.movingPiece = null
      this.capturingPiece = null
      this.checkedKing = null
      this.promotingPiece = null
      this.moveHistory = []
      this.positionHistory = []
      this.movesSinceLastCaptureOrPawn = 0
      this.enPassantTarget = null
      this.castlingState = {
        whiteKingMoved: false,
        blackKingMoved: false,
        whiteLeftRookMoved: false,
        whiteRightRookMoved: false,
        blackLeftRookMoved: false,
        blackRightRookMoved: false
      }
    },

    onSquareClick(position) {
      if (this.showPromotionDialog) {
        console.log('[点击拦截] 升变过程中禁止操作')
        return
      }

      const { row, col } = position
      const piece = this.localBoardMatrix[row][col]
      const currentSelected = this.selectedPiece

      if (currentSelected) {
        const matchingMove = this.localPossibleMoves.find(move => 
          move.row === row && move.col === col
        )

        if (matchingMove) {
          this.movePiece(currentSelected, matchingMove)
        }

        this.$emit('update:selectedPiece', null)
        this.localPossibleMoves = []
      } else if (piece && piece.color === this.currentPlayer) {
        this.$emit('update:selectedPiece', { row, col, ...piece })
        this.localPossibleMoves = this.moveCalculator.calculatePossibleMoves(row, col, piece, this.enPassantTarget, this.castlingState)
        this.$emit('update-possible-moves', this.localPossibleMoves)
      }
    },

    movePiece(from, to) {
      const piece = this.localBoardMatrix[from.row][from.col]
      const targetPiece = this.localBoardMatrix[to.row][to.col]

      // 设置移动动画状态
      this.movingPiece = { row: from.row, col: from.col }
      if (targetPiece) {
        this.capturingPiece = { row: to.row, col: to.col }
      }

      // 更新王和车的移动状态（用于王车易位）
      if (piece.type === 'king') {
        if (piece.color === 'white') {
          this.castlingState.whiteKingMoved = true
        } else {
          this.castlingState.blackKingMoved = true
        }
      } else if (piece.type === 'rook') {
        if (piece.color === 'white') {
          if (from.col === 0) this.castlingState.whiteLeftRookMoved = true
          if (from.col === 7) this.castlingState.whiteRightRookMoved = true
        } else {
          if (from.col === 0) this.castlingState.blackLeftRookMoved = true
          if (from.col === 7) this.castlingState.blackRightRookMoved = true
        }
      }

      // 处理王车易位
      if (piece.type === 'king' && to.isCastling) {
        // 移动车
        const rookFromCol = to.rookFromCol
        const rookToCol = to.rookToCol
        const rook = this.localBoardMatrix[from.row][rookFromCol]
        this.localBoardMatrix[from.row][rookToCol] = rook
        this.localBoardMatrix[from.row][rookFromCol] = null
      }

      // 处理吃过路兵
      if (piece.type === 'pawn' && to.isEnPassant) {
        this.localBoardMatrix[to.captureRow][to.captureCol] = null
      }

      // 记录吃过路兵目标
      this.enPassantTarget = piece.type === 'pawn' && to.isDoublePawnMove ? 
        { row: (from.row + to.row) / 2, col: to.col } : null

      // 执行移动
      this.localBoardMatrix[to.row][to.col] = piece
      this.localBoardMatrix[from.row][from.col] = null
      
      // 更新moveCalculator的棋盘状态
      this.moveCalculator.updateBoardMatrix(this.localBoardMatrix)

      // 处理兵的升变
      if (piece.type === 'pawn' && (to.row === 0 || to.row === 7)) {
        this.promotingPiece = { row: to.row, col: to.col }
        this.promotionPosition = { from, to }
        this.promotionColor = piece.color
        this.showPromotionDialog = true
        this.capturingPiece = null
        this.$emit('pawnPromotion', to)
        return
      }

      // 检查游戏状态
      this.checkGameStatus()

      // 触发移动完成事件
      this.$emit('pieceMoved', {
        from,
        to,
        captured: targetPiece,
        isPromotion: false
      })

      // 重置移动状态
      setTimeout(() => {
        this.movingPiece = null
        this.capturingPiece = null
      }, 500)
    },

    onPromotionSelect(type) {
        if (!this.promotionPosition || !this.promotionColor || !this.promotionPosition.from || !this.promotionPosition.to) {
          console.warn('[升变错误] 升变状态不完整')
          this.showPromotionDialog = false
          this.promotingPiece = null
          this.promotionPosition = null
          this.promotionColor = ''
          return
        }

        const piece = {
          type,
          color: this.promotionColor
        }

        // 记录被吃掉的棋子
        const capturedPiece = this.localBoardMatrix[this.promotionPosition.to.row][this.promotionPosition.to.col]

        // 保存升变位置的临时引用
        const promotionFrom = this.promotionPosition.from
        const promotionTo = this.promotionPosition.to

        // 立即更新棋盘状态
        this.$nextTick(() => {
          // 更新棋盘
          this.localBoardMatrix[promotionTo.row][promotionTo.col] = piece
          
          // 更新moveCalculator的状态
          this.moveCalculator.updateBoardMatrix(this.localBoardMatrix)

          // 重置状态
          this.showPromotionDialog = false
          
          // 强制触发视图更新
          this.$forceUpdate()
        })
        
        // 强制更新视图
        this.$forceUpdate()
        
        // 通知父组件棋盘更新
        this.$emit('updateBoardMatrix', this.localBoardMatrix)
        
        // 检查将军状态
        this.checkGameStatus()
        
        // 触发玩家回合切换事件，包含完整的移动信息
        this.$emit('pieceMoved', {
          from: promotionFrom,
          to: promotionTo,
          captured: capturedPiece,
          isPromotion: true,
          promotedTo: type
        })
        
        // 最后触发升变完成事件
        this.$emit('promotion-complete')
        
        // 重置升变相关状态
        this.showPromotionDialog = false
        this.promotingPiece = null
        this.promotionPosition = null
        this.promotionColor = ''
        
        // 再次强制更新视图
        this.$forceUpdate()
    },

    checkGameStatus() {
      const opponentColor = this.currentPlayer === 'white' ? 'black' : 'white'
      const kingPosition = this.findKing(opponentColor)
      
      if (!kingPosition) {
        this.$emit('checkmate', {
          winner: this.currentPlayer,
          reason: 'killed'
        })
        return
      }
      
      // 检查是否将军
      if (this.isKingInCheck(opponentColor)) {
        this.checkedKing = kingPosition
        this.$emit('check', { color: opponentColor })
      } else {
        this.checkedKing = null
      }
    },

    findKing(color) {
      for (let row = 0; row < 8; row++) {
        for (let col = 0; col < 8; col++) {
          const piece = this.localBoardMatrix[row][col]
          if (piece && piece.type === 'king' && piece.color === color) {
            return { row, col }
          }
        }
      }
      return null
    },

    isKingInCheck(color) {
      const kingPosition = this.findKing(color)
      if (!kingPosition) return false

      const opponentColor = color === 'white' ? 'black' : 'white'
      for (let row = 0; row < 8; row++) {
        for (let col = 0; col < 8; col++) {
          const piece = this.localBoardMatrix[row][col]
          if (piece && piece.color === opponentColor) {
            const moves = this.moveCalculator.calculatePossibleMoves(row, col, piece)
            if (moves.some(move => move.row === kingPosition.row && move.col === kingPosition.col)) {
              return true
            }
          }
        }
      }
      return false
    }
  }
}
</script>

<style>
@import './chessboard.css';
</style>